<?php

namespace app\admin\controller;

use app\admin\model\AdminCate;
use app\admin\model\AdminCateRelation;
use app\admin\model\Dictionary;
use app\admin\model\PersonRole;
use app\admin\model\PersonRoleRelation;
use app\admin\model\Project as projectModel;
use app\admin\model\TaskPersonRelation;
use app\admin\model\WorkPerson;
use app\admin\model\Task as TaskMode;
use app\admin\model\Admin as AdminModel;
use app\admin\service\JiraProject;
use JiraRestApi\Project\ProjectService;
use think\Db;
use think\Session;

class Task extends Permissions
{

    /**
     * 任务列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $taskModel = new TaskMode();
        $project_id = $this->request->param('project_id', 1, 'intval');

        $devInfoList = $taskModel->where(["project_id" => $project_id, "task_type" => ["in", Dictionary::taskTypeClass('dev')], "is_del" => 0])->order("begin_time asc")->select();
        $this->assign("devInfoList", $devInfoList);
        $testInfoList = $taskModel->where(["project_id" => $project_id, "task_type" => ["in", Dictionary::taskTypeClass('test')], "is_del" => 0])->order("begin_time asc")->select();
        $this->assign("testInfoList", $testInfoList);
        $otherInfoList = $taskModel->where(["project_id" => $project_id, "task_type" => ["in", Dictionary::taskTypeClass('other')], "is_del" => 0])->order("begin_time asc")->select();
        $this->assign("otherInfoList", $otherInfoList);

        $this->assignProjectInfo($project_id);
        $this->assignMap();

        return $this->fetch();
    }

    /**
     * 人员列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function personIndex()
    {
        $taskModel = new TaskMode();
        $project_id = $this->request->param('project_id', 0, 'intval');

        $devInfo = $taskModel->alias("t")
            ->field("t.*, pr.person_id, pr.person_name")
            ->join("tplay_task_person_relation pr", "pr.task_id = t.task_id and pr.relation_status=10", "right")
            ->where(["t.project_id" => $project_id, "task_type" => ["in", Dictionary::taskTypeClass('dev')], "is_del" => 0])->order("t.begin_time asc")->select();
        $testInfo = $taskModel->alias("t")
            ->field("t.*, pr.person_id, pr.person_name")
            ->join("tplay_task_person_relation pr", "pr.task_id = t.task_id and pr.relation_status=10", "right")
            ->where(["t.project_id" => $project_id, "task_type" => ["in", Dictionary::taskTypeClass('test')], "is_del" => 0])->order("t.begin_time asc")->select();
        $otherInfo = $taskModel->alias("t")
            ->field("t.*, pr.person_id, pr.person_name")
            ->join("tplay_task_person_relation pr", "pr.task_id = t.task_id and pr.relation_status=10", "right")
            ->where(["t.project_id" => $project_id, "task_type" => ["in", Dictionary::taskTypeClass('other')], "is_del" => 0])->order("t.begin_time desc")->select();


        $this->assign("devInfo", $devInfo);
        $this->assign("testInfo", $testInfo);
        $this->assign("otherInfo", $otherInfo);

        $this->assignProjectInfo($project_id);
        $this->assignMap();

        return $this->fetch();
    }

    /**
     * 任务列表&人员列表 公共map
     */
    private function assignMap()
    {
        $this->assign("taskTypeName", Dictionary::taskTypeName());
        $this->assign("projectLevel", Dictionary::projectLevelMap());
        $this->assign("taskStatusMap", Dictionary::taskStatusMap());
        $this->assign('projetcTypeName', Dictionary::projetcTypeName());
        $this->assign('projectStageName', Dictionary::projectStageName());
        $this->assign('projectStatusName', Dictionary::projectStatusName());
    }

    /**
     * 任务列表&人员列表 项目信息
     * @param int $project_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function assignProjectInfo($project_id = 0){
        $projectMode = new projectModel();
        $projectInfo = $projectMode->where(["project_id" => $project_id])->find();
        $this->assign("project", $projectInfo);
        $this->assign("project_id", $project_id);

        //项目经理
        $project_manager_info = AdminModel::get($projectInfo['project_manager_id']);
        $this->assign("project_manager", $project_manager_info ? $project_manager_info->nickname : "未知");

        //产品经理
        $product_manager_info = AdminModel::get($projectInfo['product_manager_id']);
        $this->assign('product_manager', $product_manager_info ? $product_manager_info->nickname : "未知");

        $jira_project_service = new JiraProject();
        $project_list = $jira_project_service->getAllProjectList();
        $product_line_map = [];
        $project_list && array_walk($project_list,function($value) use(&$product_line_map) {
            $product_line_map[$value['key']] = $value['name'];
        });
        $this->assign('productLineMap', $product_line_map);
        //dump($product_line_map);
    }

    /**
     * 创建/更新任务
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function publish()
    {
        $id = $this->request->has('task_id') ? $this->request->param('task_id', 0, 'intval') : 0;
        $project_id = $this->request->has('project_id') ? $this->request->param('project_id', 0, 'intval') : 0;
        $taskModel = new TaskMode();
        $adminModel = new AdminModel();
        $relationModel = new TaskPersonRelation();
        if ($id > 0) {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $person_idarr = $post['personId'];
                if (empty($person_idarr)) {
                    return $this->error('修改任务失败');
                }
                $relationList = $relationModel->where(['task_id' => $id, "relation_status" => 10])->select();
                $personId = [];
                foreach ($relationList as $val) {
                    $personId[] = $val['person_id'];
                }
                //获取新增的
                $new_id = [];
                foreach ($person_idarr as $per) {
                    if (!in_array($per, $personId)) {
                        $new_id[] = $per;
                    }
                }
                //获取旧的删除的
                $old_id = [];
                foreach ($personId as $pers) {
                    if (!in_array($pers, $person_idarr)) {
                        $old_id[] = $pers;
                    }
                }
                $userId = Session::get('admin');
                foreach ($old_id as $o) {
                    $relationIn = $relationModel->where(['task_id' => $id, "person_id" => $o, "relation_status" => 10])->find();
                    $old_reid = $relationIn['relation_id'];
                    $save_re['relation_status'] = 20;//解绑
                    $save_re['update_user_id'] = $userId;
                    $save_re['update_time'] = time();
                    $relationModel->where(['relation_id' => $old_reid])->update($save_re);
                }
                //关系表新增
                $add_list = [];
                foreach ($new_id as $n) {
                    $add_data = [];
                    $add_data['project_id'] = $project_id;
                    $add_data['task_id'] = $id;
                    $add_data['person_id'] = $n;
                    $personInfo = $adminModel->where(['id' => $n])->find();
                    $add_data['person_name'] = $personInfo['nickname'];
                    $add_data['relation_status'] = 10;//绑定
                    $add_data['create_user_id'] = $userId;
                    $add_data['update_user_id'] = $userId;
                    $add_data['create_time'] = time();
                    $add_data['update_time'] = time();
                    $add_list[] = $add_data;
                }
                $relationModel->allowField(true)->saveAll($add_list);


                $post['update_time'] = time();
                $post['begin_time'] = !empty($post['begin_time']) ? strtotime($post['begin_time']) : 0;
                $post['end_time'] = !empty($post['end_time']) ? strtotime($post['end_time']) : 0;
                $userId = Session::get('admin');
                $post['update_user_id'] = $userId;
                if (false == $taskModel->allowField(true)->save($post, ["task_id" => $id])) {
                    return $this->error('修改任务失败');
                } else {
                    addlog('update taskId: '.$taskModel->task_id);//写入日志
                    return $this->success('修改任务成功', "admin/task/index?project_id={$project_id}", null, 0);
                }
            } else {
                $personId = TaskPersonRelation::where(['task_id' => $id, "relation_status" => 10])->column("person_id");
                $person = $adminModel->select();
                $info = $taskModel->where(["task_id" => $id, "is_del" => 0])->find();

            }
        } else {
            //新增
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $post['create_time'] = time();
                $post['update_time'] = time();
                $post['begin_time'] = !empty($post['begin_time']) ? strtotime($post['begin_time']) : 0;
                $post['end_time'] = !empty($post['end_time']) ? strtotime($post['end_time']) : 0;
                $userId = Session::get('admin');
                $post['create_user_id'] = $userId;
                $post['update_user_id'] = $userId;

                if (empty($post['personId'])) {
                    return $this->error('选择人员');
                }
                $person_idarr = $post['personId'];
                $taskRes = $taskModel->allowField(true)->save($post);
                $task_id = $taskModel->task_id;
                $add_list = [];
                foreach ($person_idarr as $i) {
                    $add_data = [];
                    $add_data['project_id'] = $project_id;
                    $add_data['task_id'] = $task_id;
                    $add_data['person_id'] = $i;
                    $personInfo = $adminModel->where(['id' => $i])->find();
                    $add_data['person_name'] = $personInfo['nickname'];
                    $add_data['relation_status'] = 10;//绑定
                    $add_data['create_user_id'] = $userId;
                    $add_data['update_user_id'] = $userId;
                    $add_data['create_time'] = time();
                    $add_data['update_time'] = time();
                    $add_list[] = $add_data;
                }
                $relationModel->allowField(true)->saveAll($add_list);

                if (false == $taskRes) {
                    return $this->error('添加任务失败');
                } else {
                    addlog('add taskId: '.$taskModel->task_id);//写入日志
                    return $this->success('添加任务成功', "admin/task/index?project_id={$project_id}");
                }
            } else {
                $person = $adminModel->select();
                $personId = [];
                $info = null;
            }
        }
        $this->assign("presonRoleList", $this->presonRoleList());
        $this->assign("info", $info);
        $this->assign("project_id", $project_id);
        $this->assign('personInfo', $person);
        $this->assign('personIds', $personId);
        $this->assign("taskTypeName", Dictionary::taskTypeName());
        $this->assign('taskStatusMap', Dictionary::taskStatusMap());
        return $this->fetch();
    }

    /**
     * 任务分配
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taskDistribution()
    {
        if ($this->request->isPost()) {

            $taskModel = new TaskMode();
            $admin = new AdminModel();
            $relationModel = new TaskPersonRelation();
            $post = $this->request->post();
            if (!isset($post['project_id']) || empty($post['project_id'])) {
                return $this->error("项目未选择");
            }
            if (empty($post['personId'])) {
                return $this->error("人员未选择");
            }
            $personIds = $post['personId'];
            $userId = Session::get('admin');
            $data['begin_time'] = strtotime($post['begin_time']);
            $data['end_time'] = strtotime($post['end_time']);
            $data['task_type'] = $post['task_type'];
            $data['task_name'] = $post['task_name'];
            $data['project_id'] = $post['project_id'];
            $data['task_content'] = $post['task_content'] ?: '';
            $data['task_status'] = $post['task_status'];
            $data['create_user_id'] = $userId;
            $data['update_user_id'] = $userId;
            $data['create_time'] = time();
            $data['update_time'] = time();
            $taskRes = $taskModel->allowField(true)->save($data);
            if (false == $taskRes) {
                return $this->error('添加任务失败');
            }
            $task_id = $taskModel->task_id;
            foreach ($personIds as $n) {
                $add_data = [];
                $add_data['project_id'] = $post['project_id'];
                $add_data['task_id'] = $task_id;
                $add_data['person_id'] = $n;
                $personInfo = $admin->where(['id' => $n])->find();
                $add_data['person_name'] = $personInfo['nickname'];
                $add_data['relation_status'] = 10;//绑定
                $add_data['create_user_id'] = $userId;
                $add_data['update_user_id'] = $userId;
                $add_data['create_time'] = time();
                $add_data['update_time'] = time();
                $relationModel->allowField(true)->isUpdate(false)->data($add_data, true)->save();
            }
            addlog('add taskId: '.$taskModel->task_id);//写入日志
            return $this->success('添加任务成功', "admin/task/index?project_id={$post['project_id']}");
        } else {
            //获取用户信息
            $roleList = $this->presonRoleList();

            //获取项目列表
            $projectModel = new projectModel();
            $projectList = $projectModel->where(["is_del" => 0])->select();

            $this->assign("roleList", $roleList);
            $this->assign("projectList", $projectList);
            $this->assign("taskType", Dictionary::taskTypeName());
            $this->assign('taskStatus', Dictionary::taskStatusMap());
            return $this->fetch();
        }
    }

    /**
     * 人员信息 根据角色
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function presonRoleList()
    {
        $adminCateMode = new AdminCate();
        $adminCateRelationModel = new AdminCateRelation();
        //获取角色列表
        $roleList = $adminCateMode->where(['is_prd' => 0])->select();
        foreach ($roleList as &$ro) {
            $relationList = $adminCateRelationModel->where(['cate_id' => $ro['id'], "cate_status" => 1])->order('admin_name asc')->select();
            $ro['person_list'] = $relationList;
        }

        return $roleList;
    }

    /**
     * 删除任务
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if ($id) {
                $taskModel = new TaskMode();
                $taskInfo = $taskModel->where(["task_id" => $id, "is_del" => 0])->find();
                if ($taskInfo) {
                    $relationModel = new TaskPersonRelation();
                    $relation_update_date['relation_status'] = 20;//解绑
                    $relation_update_date['update_user_id'] = Session::get('admin');;
                    $relation_update_date['update_time'] = time();
                    $relationModel->where(['task_id' => $id, 'relation_status' => 10])->update($relation_update_date);
                    $taskModel->where(["task_id" => $id, "is_del" => 0])->update(['update_user_id' => Session::get('admin'), 'update_time' => time(), 'is_del' => 1]);
                    return $this->success("删除成功!");
                }
            }
            return $this->error('参数有误! 未查询到需要删除的任务...');
        } else {
            return $this->error("非法请求!!!");
        }
    }
}